/**
 * 
 */
package org.mspring.crm.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mspring.crm.convert.Convert;

/**
 * @author Gao Youbo
 * @since 2012-3-6
 * 
 */
public class ConvertUtils {

    private static String packagePath = "org.mspring.crm.convert";

    private static Map<Class, Convert<Object, Object>> map = new HashMap<Class, Convert<Object, Object>>();

    private static List<Convert> converts;

    @SuppressWarnings("unchecked")
    public static <X> X convertToClient(Object object) throws Exception {
        if (object instanceof List) {
            List<Object> list = (List<Object>) object;
            List<Object> result = new ArrayList<Object>();
            for (Object obj : list) {
                result.add(convertToClient(obj));
            }
            return (X) result;
        } else {
            String clazzName = packagePath + "." + object.getClass().getSimpleName() + "Convert";
            Class clazz = Class.forName(clazzName);
            if (map.get(clazz) == null) {
                map.put(clazz, (Convert<Object, Object>) clazz.newInstance());
            }
            Convert<Object, Object> instance = map.get(clazz);
            return (X) instance.convertToEntity(object);

        }
    }

    @SuppressWarnings("unchecked")
    public static <X> X convertToModel(Object object) throws Exception {
        if (object instanceof List) {
            List<Object> list = (List<Object>) object;
            List<Object> result = new ArrayList<Object>();
            for (Object obj : list) {
                result.add(convertToModel(obj));
            }
            return (X) result;
        } else {
            String simpleName = object.getClass().getSimpleName();
            String convertSimpleName = simpleName + "Convert";
            String clazzName = packagePath + "." + convertSimpleName;
            Class clazz = Class.forName(clazzName);
            if (map.get(clazz) == null) {
                map.put(clazz, (Convert<Object, Object>) clazz.newInstance());
            }
            Convert<Object, Object> instance = map.get(clazz);
            return (X) instance.convertToModel(object);
        }

    }
}
